<template>
    <div>
        <el-alert v-if="!props.hideAlter" :closable="false" :type="state.disable?'error':'success'" show-icon style="height: 32px;margin-bottom: 8px">
            <template #title>
                <div v-if="!state.disable">
                    验证码将发送至 <strong>{{ props.defaultEmail }}</strong> 请注意查收
                </div>
                <div v-if="state.disable">
                    无法发送验证码，请填写个人邮箱！
                </div>
            </template>
        </el-alert>
        <el-input
                v-model="state.value"
                :disabled="state.disable"
                clearable
                placeholder="请输入邮箱验证码"
        >
            <template #append>
                <el-button @click="send">发送验证码</el-button>
            </template>
        </el-input>
    </div>
</template>

<script lang="ts">
import {BaseApi} from "~/api/util/BaseService";
import {defineComponent, reactive} from "vue";
import {useUserStore} from "~/store/modulers/user";
import {storeToRefs} from "pinia";


interface Props {
    email?: string;
    defaultEmail?: string;
    modelValue?: string;
    hideAlter?: boolean;
}

const userStore = useUserStore();
const {user} = storeToRefs(userStore);
let email = String(user.value.email);

export default defineComponent({
    emits: ["update:modelValue"],
    props: {
        email: {
            type: String,
        },
        modelValue: {
            type: String,
        },
        hideAlter: {
            type: Boolean,
            default: false,
        },
        defaultEmail: {
            type: String,
            default: email,
        },
    },
    setup(props) {

        const state = reactive({
            email: "",
            disable: false,
            value: "",
        });

        class SendMailApi extends BaseApi<any> {
            baseUrl: string = "";
        }

        const mailApi = new SendMailApi();

        function send() {
            mailApi.sendCodeByMail(props.hideAlter ? state.email : props.defaultEmail);
        }

        return {
            props, state, send,
        };
    },
    watch: {
        "state.value"(value) {
            this.$emit("update:modelValue", value);
        },
        "props.email"(value) {
            if (value) {
                this.state.email = value;
            }
        },
    },
    mounted() {
        if (!this.props.email && !email) {
            this.state.disable = true;
        }
    },
});
</script>

<style lang="scss" scoped>

</style>
